package com.pac.user.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.common.tools.MD5Tools;
import com.common.tools.MailTools;
import com.common.tools.StringTools;
import com.common.tools.TimeTools;
import com.common.util.ErrorNumber;
import com.common.util.LogicException;
import com.common.util.PropertyUtils;
import com.pac.doctor.bean.DoctorBean;
import com.pac.doctor.service.DoctorService;
import com.pac.role.bean.RoleBean;
import com.pac.role.bean.RoleUserRelBean;
import com.pac.role.service.RoleUserRelService;
import com.pac.user.UserKeyContent;
import com.pac.user.bean.UserBean;
import com.pac.user.bean.UserDetailBean;
import com.pac.user.dao.UserDao;
import com.pac.user.dao.UserDetailDao;
import com.pac.user.service.UserService;

/**
 * 用户Service接口实现
 * 
 * @author lujun.chen
 * @version [版本号, 2015年2月13日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Service(value = "userService")
public class UserServiceImpl implements UserService {

	private static Logger logger = Logger.getLogger(UserServiceImpl.class);

	@Autowired
	private UserDao userDao;
	
	@Autowired
	private UserDetailDao userDetailDao;

	@Autowired
	private RoleUserRelService roleUserRelService;
	
	@Autowired
	private DoctorService doctorService;
	
	/** 查询单个用户信息 */

	@Override
	public UserBean findUser(UserBean userBean) {
		List<UserBean> userList = userDao.queryUser(userBean);
		UserBean userBeanR = null;
		if (null != userList && userList.size() > 0) {
			userBeanR = userList.get(0);
		}
		return userBeanR;
	}

	/** 添加用户，同时绑定用户角色 */

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public String addUser(UserBean userBean) {

		if (null == userBean) {
			logger.error("添加用户出错，参数为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "参数为空");
		}

		if (StringTools.isNull(userBean.getUserName())) {
			logger.error("添加用户出错，用户名为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "用户名为空");
		}

		if (StringTools.isNull(userBean.getPassword())) {
			logger.error("添加用户出错，密码为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "密码为空");
		}

		// 用户状态默认设置为：0启用
		if (StringTools.isNull(userBean.getState())) {
			userBean.setState(UserKeyContent.USER_STATUS_ACTIVE);
		}

		// 设置账号过期时间
		if (StringTools.isNull(userBean.getEndDate())) {
			userBean.setEndDate(UserKeyContent.USER_END_DATE);
		}

		// 密码MD5加密
		String pwdMd5 = MD5Tools.MD5(userBean.getPassword());
		pwdMd5 = pwdMd5.toLowerCase();
		userBean.setPassword(pwdMd5);

		userBean.setCreateDate(TimeTools.now());

		String userId = userDao.addUser(userBean);

		// 2用户绑定角色
		List<RoleBean> roleList = userBean.getRoleList();
		if (null != roleList && roleList.size() > 0) {
			for (RoleBean role : roleList) {
				RoleUserRelBean roleUserRel = new RoleUserRelBean();
				roleUserRel.setRoleId(role.getId());
				roleUserRel.setUserId(userId);
				roleUserRelService.addRoleUserRel(roleUserRel);
			}
		}

		return userId;
	}

	/** 用户注册 */

	@Override
	public boolean register(UserBean userBean, String roleId) {

		if (null == userBean) {
			logger.error("用户注册出错，参数为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "参数为空");
		}

		if (StringTools.isNull(userBean.getUserName())) {
			logger.error("用户注册出错，用户名为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "用户名为空");
		}

		if (StringTools.isNull(userBean.getPassword())) {
			logger.error("用户注册出错，密码为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "密码为空");
		}

		if (StringTools.isNull(roleId)) {
			logger.error("用户注册出错，角色ID为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "角色ID为空");
		}

		// 用户绑定角色
		List<RoleBean> roleList = new ArrayList<RoleBean>();
		RoleBean roleBean = new RoleBean();
		roleBean.setId(roleId);
		roleList.add(roleBean);
		userBean.setRoleList(roleList);

		// 添加用户
		addUser(userBean);

		return true;
	}

	@Override
	public List<UserBean> queryUser(UserBean userBean) {
		return userDao.queryUser(userBean);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean delUserById(String userId) {
		if (StringTools.isNull(userId)) {
			logger.error("删除用户出错，用户ID为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "删除用户出错，用户ID为空");
		}

		if (UserKeyContent.USER_ID_SYSTEM.equals(userId)) {
			logger.error("删除用户出错，system不允许被删除");
			throw new LogicException(ErrorNumber.LOGIC_EXCEPTION,
					"删除用户出错，system不允许被删除");
		}

		// 删除用户绑定的角色
		RoleUserRelBean roleUserRelBean = new RoleUserRelBean();
		roleUserRelBean.setUserId(userId);
		roleUserRelService.delRoleUserRel(roleUserRelBean);

		// 删除用户
		UserBean userBean = new UserBean();
		userBean.setId(userId);

		return userDao.delUser(userBean);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean editState(String userId, String state) {
		if (StringTools.isNull(userId)) {
			logger.error("修改用户状态出错，用户ID为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL,
					"修改用户状态出错，用户ID为空");
		}

		if (StringTools.isNull(state)) {
			logger.error("修改用户状态出错，用户状态为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL,
					"修改用户状态出错，用户状态为空");
		}

		if ((!UserKeyContent.USER_STATUS_ACTIVE.equals(state))
				&& (!UserKeyContent.USER_STATUS_INACTIVE.equals(state))) {
			logger.error("修改用户状态出错，用户状态只能是0或1");
			throw new LogicException(ErrorNumber.LOGIC_EXCEPTION,
					"修改用户状态出错，非法操作");
		}

		if (UserKeyContent.USER_ID_SYSTEM.equals(userId)
				&& UserKeyContent.USER_STATUS_INACTIVE.equals(state)) {
			logger.error("修改用户状态出错，system不允许被停用");
			throw new LogicException(ErrorNumber.LOGIC_EXCEPTION,
					"修改用户状态出错，system不允许被停用");
		}

		
		UserBean userBean = new UserBean();
		userBean.setId(userId);
		//查询用户信息
		UserBean userBeanR=findUser(userBean);
		if(null==userBeanR)
		{
			logger.error("未找到用户ID["+userId+"]对应的用户信息");
			throw new LogicException(ErrorNumber.LOGIC_EXCEPTION,"未找到对应的用户信息");
		}
		
		
		//修改用户状态
		userBean.setState(state);
		boolean res = userDao.editUser(userBean);
		
		if(res&&UserKeyContent.USER_STATUS_ACTIVE_WILL.equals(userBeanR.getState()))
		{
			//查询用户详细信息
			UserDetailBean userDetailBean=new UserDetailBean();
			userDetailBean.setId(userBeanR.getUserDetailId());
			List<UserDetailBean> userDetailList=userDetailDao.queryUserDetail(userDetailBean);
			if(null!=userDetailList&&userDetailList.size()>0)
			{
				userDetailBean=userDetailList.get(0);
				String userEmail=userDetailBean.getEmail();
				if(!StringTools.isNull(userEmail))
				{
					String title="宽仁妇孺关怀PAC账号激活";
					StringBuffer sbContent=new StringBuffer();
					sbContent.append(userBeanR.getNickname());
					sbContent.append("：");
					sbContent.append("<br/>&nbsp;&nbsp;&nbsp;&nbsp;");
					sbContent.append("您好！");
					sbContent.append("<br/>&nbsp;&nbsp;&nbsp;&nbsp;");
					sbContent.append("您在宽仁妇孺关怀PAC平台注册的账号已经激活，点击下面链接登录。");
					sbContent.append("<br/>&nbsp;&nbsp;&nbsp;&nbsp;");
					String demainUrl=PropertyUtils.getValue("system.domain.url");
					sbContent.append(demainUrl);
					MailTools.getInstance().send(userEmail, title, sbContent.toString());
				}
			}
		}

		return res;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean editUser(UserBean userBean) {
		if (null == userBean) {
			logger.error("修改用户信息出错，参数为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "修改用户信息出错，参数为空");
		}

		if (StringTools.isNull(userBean.getId())) {
			logger.error("修改用户信息出错，用户ID为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL,
					"修改用户信息出错，用户ID为空");
		}

		if (StringTools.isNull(userBean.getRoleIds())) {
			logger.error("修改用户信息出错，用户未绑定角色");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL,
					"修改用户信息出错，用户未绑定角色");
		}

		// 密码MD5加密
		if (!StringTools.isNull(userBean.getPassword())) {
			String passwordMD5 = MD5Tools.MD5(userBean.getPassword());
			passwordMD5 = passwordMD5.toLowerCase();
			userBean.setPassword(passwordMD5);
		}

		// 允许登录时间为空，设置默认值为当前时间
		if (StringTools.isNull(userBean.getCreateDate())) {
			String startDate = TimeTools.now();
			userBean.setCreateDate(startDate);
		}

		if (StringTools.isNull(userBean.getEndDate())) {
			userBean.setEndDate(UserKeyContent.USER_END_DATE);
		}

		// 启用时间不能小于结束时间
		Date startDate = TimeTools.toDate(userBean.getCreateDate(),
				TimeTools.DATE_FORMAT_DEFAULT);
		Date endDate = TimeTools.toDate(userBean.getEndDate(),
				TimeTools.DATE_FORMAT_DEFAULT);
		if (endDate.before(startDate)) {
			logger.error("修改用户出错，启用时间[" + userBean.getCreateDate()
					+ "]不能大于到期时间[" + userBean.getEndDate() + "]");
			throw new LogicException(ErrorNumber.LOGIC_EXCEPTION,
					"修改用户出错，启用时间[" + userBean.getCreateDate() + "]不能大于到期时间["
							+ userBean.getEndDate() + "]");
		}

		// 删除原来的人员角色关联关系，重新添加
		RoleUserRelBean roleUserRelBean = new RoleUserRelBean();
		roleUserRelBean.setUserId(userBean.getId());
		roleUserRelService.delRoleUserRel(roleUserRelBean);

		String roleIds = userBean.getRoleIds();
		String[] roleIdArr = roleIds.split(",");
		for (String roleId : roleIdArr) {
			roleUserRelBean.setRoleId(roleId);
			roleUserRelService.addRoleUserRel(roleUserRelBean);
		}

		return userDao.editUser(userBean);
	}

	@Override
	public boolean editUserBase(UserBean userBean) {

		if (null == userBean) {
			logger.error("修改用户基本信息出错，参数为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "参数为空");
		}

		if (StringTools.isNull(userBean.getId())) {
			logger.error("修改用户基本信息出错，用户ID为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "用户ID为空");
		}

		// 密码MD5加密
		if (!StringTools.isNull(userBean.getPassword())) {
			String passwordMD5 = MD5Tools.MD5(userBean.getPassword());
			passwordMD5 = passwordMD5.toLowerCase();
			userBean.setPassword(passwordMD5);
		}

		return userDao.editUser(userBean);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean doctorRegister(UserBean userBean, String roleId,
			DoctorBean doctorBean) {

		if (null == userBean) {
			logger.error("医生注册出错，参数为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "参数为空");
		}

		if (StringTools.isNull(userBean.getUserName())) {
			logger.error("医生注册出错，用户名为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "用户名为空");
		}

		if (StringTools.isNull(roleId)) {
			logger.error("医生注册出错，角色ID为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "角色ID为空");
		}

		if (null == doctorBean) {
			logger.error("医生注册出错，医生信息为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "医生信息为空");
		}

		// 用户绑定角色
		List<RoleBean> roleList = new ArrayList<RoleBean>();
		RoleBean roleBean = new RoleBean();
		roleBean.setId(roleId);
		roleList.add(roleBean);
		userBean.setRoleList(roleList);
		
		//添加用户详细
		UserDetailBean	userDetailBean=doctorBean;
		userDetailBean.setCreateDate(TimeTools.now());
		String userDetailId=userDetailDao.addUserDetail(userDetailBean);

		// 添加用户
		userBean.setUserDetailId(userDetailId);
		userBean.setNickname(doctorBean.getName());
		userBean.setState(UserKeyContent.USER_STATUS_ACTIVE_WILL);
		String userId=addUser(userBean);
		
		//添加医生信息
		doctorBean.setCreateDate(TimeTools.now());
		doctorBean.setDescription(doctorBean.getIntroduction());
		doctorBean.setUserId(userId);
		doctorService.addDoctor(doctorBean);
		
		//给用户发送通知邮件
		if(!StringTools.isNull(doctorBean.getEmail()))
		{
			String receiver=doctorBean.getEmail();
			String title="宽仁妇孺关怀PAC注册";
			StringBuffer sbContext=new StringBuffer();
			sbContext.append(doctorBean.getName());
			sbContext.append("：");
			sbContext.append("<br/>");
			sbContext.append("感谢您注册宽仁妇孺关怀PAC，管理员会尽快审核您的资料，审核结果会发送到您的邮箱，请耐心等待。");
			
			MailTools.getInstance().send(receiver, title, sbContext.toString());
		}

		return true;
	}
	
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean editPassword(UserBean userBean, String oldPassword,
			String newPassword) throws LogicException {

		if (null == userBean) {
			logger.error("修改密码出错，用户信息为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "修改密码出错，用户信息为空");
		}

		if (StringTools.isNull(oldPassword)) {
			logger.error("修改密码出错，原密码为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "修改密码出错，原密码为空");
		}

		if (StringTools.isNull(newPassword)) {
			logger.error("修改密码出错，新密码为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "修改密码出错，新密码为空");
		}

		// MD5加密
		String oldPasswordMD5 = MD5Tools.MD5(oldPassword);
		oldPasswordMD5 = oldPasswordMD5.toLowerCase();

		String newPasswordMD5 = MD5Tools.MD5(newPassword);
		newPasswordMD5 = newPasswordMD5.toLowerCase();

		if (!oldPasswordMD5.equals(userBean.getPassword())) {
			logger.error("修改密码出错，原密码错误");
			throw new LogicException(ErrorNumber.LOGIC_EXCEPTION,
					"修改密码出错，原密码错误");
		}

		// 更新密码入库
		UserBean userBeanE = new UserBean();
		userBeanE.setId(userBean.getId());
		userBeanE.setPassword(newPasswordMD5);

		boolean result = userDao.editUser(userBeanE);
		if (result) {
			// 修改成功，把修改后的用户信息放入session中，上一层处理
			userBean.setPassword(newPasswordMD5);
		}

		return result;
	}

}
